package TDATopFive;

public class TopCinco<K,V> implements TopFive<K,V> {
	private Entry<K,V>[] bucket;
	private Comparador comp;
	private int cant;
	
	public TopCinco(Comparador c){
		comp=c;
		cant=0;
		bucket=new Entry[5]; 
		for(int i=0;i<bucket.length;i++)
			bucket[i]=null;
	}
	public int size(){
		return cant;
	}
	
	public void insert(K key, V value) {
		boolean insertado=false;
		for(int i=0;i<cant;i++){
			if(value.equals(bucket[i].getValue())){
				bucket[i].setKey(key);
				burbujadesde(i);
				insertado=true;
				}
		}
		
		if(!insertado)
			if(bucket.length>cant){
				bucket[cant]=new Entrada(key,value);
				burbujadesde(cant);
				cant++;
			}
			else
				if(0<comp.compare(key,bucket[4].getKey())){
					bucket[4].setKey(key);
					bucket[4].setValue(value);
					burbujadesde(cant-1);
				}
			
		}
			
		
	
	private void burbujadesde(int pos){
		boolean ordenado=false;
		Entry<K,V> aux;
		while(!ordenado && pos!=0 && pos<bucket.length){
			if(0<=comp.compare(bucket[pos].getKey(),bucket[pos-1].getKey())){
				aux=bucket[pos-1];
				bucket[pos-1]=bucket[pos];
				bucket[pos]=aux;
				pos--;
				}
			else
				ordenado=true;
				
		}
	}
	public Entry<K, V> getpos(int pos) {
		if (bucket[pos]!=null)
			return bucket[pos];
		else
		return null;
	}
	

}
